$(function () {

	$.init();
	var param = parseUrlSearch();
	var cache = {};
	renderAddress();
	renderOrder();

	$(document).on('click', '.j-refund', onRefund);
	$(document).on('click', '.j-rebuy', onRebuy);
	$(document).on('click', '.j-sure', onSure);
	$(document).on('click', '.j-cancel', onCancel);
	$(document).on('change', '.modal-text input', onRadio);

	function onSure () {
		$.confirm('您确定收到货物了吗？', function () {
			$.ajax({
				url: HOST + '/api/order/finish',
				type: 'post',
				data: JSON.stringify({
					orderCode: param.orderCode
				}),
				success: function (res) {
					renderOrder();
				}
			});
		});	
	}

	function onCancel () {
		$.confirm('您确定删除该订单？', function () {
			$.ajax({
				url: HOST + '/api/order/delete',
				type: 'post',
				data: JSON.stringify({
					orderCode: param.orderCode
				}),
				success: function (res) {
					renderOrder();
				}
			});
		});
	}

	function onRebuy () {
		sessionStorage.setItem('details', JSON.stringify(cache.details));
		sessionStorage.setItem('total', cache.totalAmount);
		window.location = './product_sure.html?from=orderdetail&orderCode='+param.orderCode;
	}

	function onRefund () {
		$.confirm( '<div style="text-align: left;">确定要退款吗？若确定，请选择退货原因。</div>\
					<input type="radio" name="reason" value="不想要了"> 不想要了\
					<br>\
					<input type="radio" name="reason" value="迟迟不发货"> 迟迟不发货\
					<br>\
					<input type="radio" name="reason" value="3"> 其他\
					<textarea></textarea>', function(elem) {
			var val = $(elem).find('input[name="reason"]:checked').val();
			if (val == 3) {
				val = $(elem).find('textarea').val();
			}
			
			if(!val) {
                $.alert('内容不能为空！');
                return;
            }
            // renderOrder();
            $.ajax({
				url: HOST + '/api/order/refund',
				type: 'post',
				data: JSON.stringify({
					orderCode: param.orderCode,
					reason: val
				}),
				success: function (res) {
					renderOrder();
				}
			});
		});
	}

	function onRadio (e) {
		if ($(e.target).val() == 3) {
			$('.modal-text textarea').show();
		}else {
			$('.modal-text textarea').hide();
		}
	}

	function renderAddress () {
		fetchAddress(function (address) {
			isHaveAddress = !!address.addressInfo;
			var html = '<div class="name">您还没有新建地址呦</div><div class="phone"></div><div class="address nowrap"></div><div class="btn j-updateAddress">新建收货地址</div>';
			if (isHaveAddress) {
				address = JSON.parse(address.addressInfo);
				html = getAddressHtml(address);
			}
			$('.address-wrap').html(html);
		});
	}

	function fetchAddress (callback) {
		$.ajax({
			url: HOST + '/api/user/address/get',
			data: {
				openid: SELFID
			},
			success: function (res) {
				callback && callback(res.content);
			}
		});
	}

	function getAddressHtml (data) {
		return '<div class="name">'+data.name+'</div>\
				<div class="phone">'+data.phone+'</div>\
				<div class="address nowrap">'+data.area+' '+data.address+'</div>';
	}

	function renderOrder () {
		fetchOrder(function (data) {
			cache = data;
			var list = data.details.reduce(function (memo, detail) {
				return memo + getProductHtml(detail);
			}, '');
			var total = '';
			var btn = '';
			// data.orderStatus = 25;
			if (data.orderStatus == 20) {
				total = getTotalHtml1(data);
				btn = getBtnHtml1();
			}else if (data.orderStatus == 25) {
				total = getTotalHtml2(data);
				btn = getBtnHtml2();
			}else if (data.orderStatus == 30) {
				total = getTotalHtml3(data);
				btn = getBtnHtml3();
			}else if (data.orderStatus == 60) {
				total = getTotalHtml4(data);
				btn = getBtnHtml4();
			}else if (data.orderStatus == 50) {
				total = getTotalHtml5(data);
			}
			$('.content ul').html(list + total);
			$('.buy-wrap').html(btn);
		});
	}

	function fetchOrder (callback) {
		$.ajax({
			url: HOST + '/api/order/get',
			data: {
				orderCode: param.orderCode
			},
			success: function (res) {
				callback && callback(res.content);
			}
		});
	}

	function renderProducts () {
		cacheSkus = JSON.parse(sessionStorage.getItem('details'));

		var html = cacheSkus.reduce(function (memo, detail) {
			return memo + getProductHtml(detail);
		}, '');
		$('.content ul').html(html);
		$('.buy-wrap .total span').html(+sessionStorage.getItem('total') + 10);
	}

	function getProductHtml (detail) {
		return '<li class="item" data-id="">\
					<div class="item_img">\
						<img src="'+detail.skuImage+'">\
					</div>\
					<div class="item_info">\
						<div class="tit">'+detail.skuName+'</div>\
						<div><span class="price">'+detail.price+' * '+ detail.qty + '</span></div>\
					</div>\
				</li>';
	}

	function getTotalHtml1(data) {
		return '<div class="order_desc">\
					<div class="label">订单编号</div>\
					<div class="value">'+data.orderCode+'</div>\
				</div>\
				<div class="order_desc">\
					<div class="label">商品总额</div>\
					<div class="value">'+data.totalAmount+'</div>\
				</div>\
				<div class="order_desc">\
					<div class="label">快递费用</div>\
					<div class="value">'+(data.isExpress?10:0)+'</div>\
				</div>\
				<div class="order_desc">\
					<div class="label">发货时间</div>\
					<div class="value">预计 '+moment(data.createdAt * 1000 + 86400 * 1000 * 3).format('YYYY-MM-DD')+' 前</div>\
				</div>';
	}
	function getTotalHtml2(data) {
		return '<div class="order_desc">\
					<div class="label">订单编号</div>\
					<div class="value">'+data.orderCode+'</div>\
				</div>\
				<div class="order_desc">\
					<div class="label">商品总额</div>\
					<div class="value">'+data.totalAmount+'</div>\
				</div>\
				<div class="order_desc">\
					<div class="label">快递费用</div>\
					<div class="value">'+(data.isExpress?10:0)+'</div>\
				</div>\
				<div class="order_desc">\
					<div class="label">发货状态</div>\
					<div class="value">已发货</div>\
				</div>\
				<div class="order_desc">\
					<div class="label">快递公司</div>\
					<div class="value">'+(data.expressCompany||'暂无快递')+'</div>\
				</div>\
				<div class="order_desc">\
					<div class="label">快递编号</div>\
					<div class="value">'+(data.expressCode||'暂无编号')+'</div>\
				</div>';
	}
	function getTotalHtml3(data) {
		return '<div class="order_desc">\
					<div class="label">订单编号</div>\
					<div class="value">'+data.orderCode+'</div>\
				</div>\
				<div class="order_desc">\
					<div class="label">商品总额</div>\
					<div class="value">'+data.totalAmount+'</div>\
				</div>\
				<div class="order_desc">\
					<div class="label">快递费用</div>\
					<div class="value">'+(data.isExpress?10:0)+'</div>\
				</div>\
				<div class="order_desc">\
					<div class="label">发货公司</div>\
					<div class="value">'+(data.expressCompany||'暂无快递')+'</div>\
				</div>\
				<div class="order_desc">\
					<div class="label">快递编号</div>\
					<div class="value">'+(data.expressCode||'暂无编号')+'</div>\
				</div>\
				<div class="order_desc">\
					<div class="label">签收状态</div>\
					<div class="value">'+(data.signState||'暂无状态')+'</div>\
				</div>';
	}
	function getTotalHtml4(data) {
		return '<div class="order_desc">\
					<div class="label">订单编号</div>\
					<div class="value">'+data.orderCode+'</div>\
				</div>\
				<div class="order_desc">\
					<div class="label">退款原因</div>\
					<div class="value" data-val="1">'+(data.closeReason||'暂无退货原因')+'</div>\
				</div>';
	}
	function getTotalHtml5(data) {
		return '<div class="order_desc">\
					<div class="label">订单编号</div>\
					<div class="value">'+data.orderCode+'</div>\
				</div>\
				<div class="order_desc">\
					<div class="label">退款总额</div>\
					<div class="value">'+data.totalAmount+'</div>\
				</div>\
				<div class="order_desc">\
					<div class="label">退款状态</div>\
					<div class="value" data-val="1">退款中</div>\
				</div>';
	}
	function getBtnHtml1 () {
		return '<div class="left j-rebuy">再次购买</div><div class="right j-refund">申请退款</div>';
	}
	function getBtnHtml2 () {
		return '<div class="left j-sure">确认收货</div><div class="right j-refund">申请退款</div>';
	}
	function getBtnHtml3 () {
		return '<div class="left j-rebuy">再次购买</div><div class="right j-cancel">删除订单</div>';
	}
	function getBtnHtml4 () {
		return '<div class="left j-rebuy">再次购买</div><div class="right j-cancel">删除订单</div>';
	}
})
